import store from '../store/index.js'

const http = function (opt){
    let header = {}
    if(opt.contentType){
        header['content-type'] = opt.contentType
    }
    if(opt.header){
        Object.assign(header, opt.header)
    }
    
    
    
    return new Promise((resolve, reject)=>{
        const excludes = ['https://api.cnblogs.com/token']
        
        if(!excludes.includes(opt.url)){
            if(store.state.token === null){
                reject('没有权限,请联系开发者')
            }else{
                const now = new Date().getTime() -2*2000;
                if( now > store.state.token.expires ){
                    store.dispatch('getTokenDefault')
                }
                header['Authorization'] = store.state.token.token
                
                console.log(header, '123')
            }
        }
        const opts = {
            method: opt.method || "GET",
            url: opt.url,
            data: opt.data,
            header,
            success: res => {
                console.log(opts.url)
                console.log(opts.header)
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        }
        uni.request(opts)
    })
}

export default http
